using UnityEngine;
using System.Collections;

public class SpriteAnimado : MonoBehaviour {
	public int uvTieX = 24;
    private int uvTieY = 1;
    public int fps = 10;
    
    private Vector2 size;
    private Renderer myRenderer;
    private int lastIndex = -1;
    
    void Start () 
    {
        size = new Vector2 (1.0f / uvTieX , 1.0f / uvTieY);
        myRenderer = renderer;
        if(myRenderer == null)
            enabled = false;
    }
    // Update is called once per frame
    void Update()
    {
        // Calculate index
        int index = (int)(Time.timeSinceLevelLoad * fps) % (uvTieX * uvTieY);
        if(index != lastIndex)
        {
            // split into horizontal and vertical index
            int uIndex = index % uvTieX;
            int vIndex = index / uvTieX;
      
            // build offset
            // v coordinate is the bottom of the image in opengl so we need to invert.
            Vector2 offset = new Vector2 (uIndex * size.x, 1.0f - size.y - vIndex * size.y);
            
            myRenderer.material.SetTextureOffset ("_MainTex", offset);
            myRenderer.material.SetTextureScale ("_MainTex", size);
            
            lastIndex = index;
        }
    }
}
